package org.itboys.mobile.service.mongo.weixin.member;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.encryption.Digests;
import org.itboys.commons.utils.image.ImageUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.member.SundayMemberDto;
import org.itboys.mobile.dto.member.SundayWeixinMemberDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.service.mongo.mobile.common.SundayMobileCidService;
import org.itboys.mobile.service.mongo.mobile.common.SundayMobileCodeService;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2017/12/7.
 * @author 朱坤涛
 * dec:会员相关，微信版
 */
@Service
public class SundayWeixinMemberService extends BaseMongoService<SundayMember> {

    @Autowired
    private SundayMobileCodeService codeService;
    @Autowired
    private ResourceHolder resourceHolder;
    @Autowired
    private SundayMobileCidService cidService;

    @Resource(name="weixinDS")
    private MongoDataSource mongoDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return mongoDataSource;
    }
    @Override
    protected Class<SundayMember> getEntityClass() {
        return SundayMember.class;
    }

    /**
     * 第三方登陆,第一步。只传入第三方信息。农厨第三方登陆需要绑定手机号
     * @param thirdType
     * @param unionId
     * @return
     */
    public SundayWeixinMemberDto loginWithThirdOne(Integer thirdType, String unionId){
        //校验用户
        Map<String, Object> param =new HashMap<String,Object>();
        param.clear();
        param.put("isDeleted",0);
        //校验第三方unionId
        if(thirdType== SundayCommonConstants.third_type_weixin){
            param.put("weixinUnionId",unionId);
        }else{
            throw new ErrorException("登陆类型错误");
        }
        List<SundayMember> oldMembers = super.list(param);
        if(ListUtil.isNull(oldMembers)){
            //如果为空，调用第三方登陆，第二步
            return null;
        }
        return packageDtoSingle(oldMembers.get(0));
    }
    /**
     * 第三方登陆,第二步。传入第三方信息和手机号。农厨第三方登陆需要绑定手机号
     * @param thirdType
     * @param unionId
     * @param mobile
     * @return
     */
    public SundayWeixinMemberDto loginWithThirdTwo(Integer thirdType,String nickName,String image, String unionId, String mobile,String code) {

        //检验验证码
        int reulct_code =codeService.checkCode(mobile,code,SundayCommonConstants.validate_code_type_login);
        if(reulct_code!=0){
            throw new ErrorException("验证码错误");
        }
        //校验用户
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("mobile",mobile);
        List<SundayMember> oldMembers = super.list(param);
        if(ListUtil.isNull(oldMembers)){
            //如果为空，调用第三方登陆，第三步
            return null;
        }
        //获取第三方信息。头像，昵称，unionId。替换用户的信息
        SundayMember member = oldMembers.get(0);
        member.setNickName(nickName);
        //保存unionId
        if(thirdType==SundayCommonConstants.third_type_weixin){
            member.setWeixinUnionId(unionId);
        }
        //获取第三方头像。半链接
        String random=String.valueOf(new Date().getTime());
        //如果当前项目的上传文件目录下没有logo文件夹，请自行创建。此文件夹存放的是默认的头像和第三方登陆用户头像
        String savePath = resourceHolder.getStringValue("fileUploadPath")+"/logo/"+random+".jpg";
        ImageUtils.buildImg(savePath,image);
        member.setImage("/logo/"+random+".jpg");
        super.updateExceptEmpty(member.getId(),member);
        SundayWeixinMemberDto memberDto=packageDtoSingle(member);

        return memberDto;
    }

    /**
     * 第三方登陆,第三步。传入第三方信息，手机号，密码。农厨第三方登陆需要绑定手机号
     * @param thirdType
     * @param nickName
     * @param image
     * @param unionId
     * @param mobile
     * @param code
     * @param password
     * @return
     */
    public SundayWeixinMemberDto loginWithThirdThree(Integer thirdType,String nickName,String image, String unionId, String mobile,String code,String password) {
        //校验用户
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("isDeleted",0);
        param.put("mobile",mobile);
        //校验第三方unionId
        if(thirdType==SundayCommonConstants.third_type_weixin){
            param.put("weixinUnionId",unionId);
        }else{
            throw new ErrorException("登陆类型错误");
        }
        List<SundayMember> oldMembers = super.list(param);
        SundayMember member = new SundayMember();
        //创建用户
        if(ListUtil.isNull(oldMembers)){
            member.setIsDeleted(0);
            member.setStatus(0);
            member.setUserName(NumberUtil.generateNumber("APP"));
            member.setUserType(SundayCommonConstants.USER_TYPE_MEMBER);
            member.setMobile(mobile);
            member.setNickName(nickName);
            //member.setParentId(0l);
            //获取第三方头像。半链接
            String random=String.valueOf(new Date().getTime());
            //如果当前项目的上传文件目录下没有logo文件夹，请自行创建。此文件夹存放的是默认的头像和第三方登陆用户头像
            String savePath = resourceHolder.getStringValue("fileUploadPath")+"/logo/"+random+".jpg";
            ImageUtils.buildImg(savePath,image);
            member.setImage("/logo/"+random+".jpg");
            //保存unionId
            if(thirdType==SundayCommonConstants.third_type_weixin){
                member.setWeixinUnionId(unionId);
            }
            member.setPassword(Digests.md5(password));
            super.save(member);
            //返回用户信息。此步骤是避免接口端误操作第二步。
        }else{
            member=oldMembers.get(0);
        }
        SundayWeixinMemberDto memberDto=packageDtoSingle(member);
        //设置用户的token。暂时是用户的秘密
        // memberDto.setToken(member.getPassword());
        return memberDto;
    }

    /**
     * 退出登录。删除CID
     * @param memberId
     */
    public void logout(long memberId){
        cidService.clear(memberId);
    }

    /**
     * 修改个人信息
     * @param memberId
     * @param  nickName
     * @param mobileName
     * @param address
     * @param email
     * @param image
     * @param idCard
     * @param desc
     */
    public SundayWeixinMemberDto update(Long memberId, String nickName, String mobileName, String address, String email,
                                  String image, String idCard, String desc){

        SundayMember member = new SundayMember();
        member.setId(memberId);
        member.setNickName(nickName);
        member.setMobileName(mobileName);
        member.setAddress(address);
        //  member.setEmail(email);
        member.setImage(image);
        // member.setIdCard(idCard);
        member.setDesc(desc);
        super.updateExceptEmpty(memberId,member);
        return packageDtoSingle(super.getById(memberId));
    }

    /**
     * 组装用户DTO。逻辑可以自定义
     */
    public SundayWeixinMemberDto packageDtoSingle(SundayMember member) {
        SundayWeixinMemberDto memberDto =new SundayWeixinMemberDto(
                member.getId(),member.getWeixinUnionId(),member.getWeixinOpenId(),member.getIsRegister(),member.getIsGuanzhu());
        return  memberDto;
    }
}
